/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BorrarTestsFrame.java
 *
 * Created on 11-ene-2012, 13:45:25
 */
package occho.view;

import java.awt.Color;
import java.sql.SQLException;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import occho.model.Asignatura;
import occho.model.FachadaGestionTest;
import occho.model.Test;
import occho.model.Usuario;
import occho.view.resources.Messages;

/**
 *
 * @author Migue
 */
public class BorrarTestsFrame extends javax.swing.JInternalFrame implements Internacionalizable {
    private Usuario profesor;
    private OcchoView view;
    private FachadaGestionTest fachada;
    private DefaultMutableTreeNode top ;
    
    /** Creates new form BorrarTestsFrame
     * @param view 
     */
    public BorrarTestsFrame(OcchoView view)  {
        this.profesor = view.getUsuario();
        this.view = view;
        this.fachada = new FachadaGestionTest(profesor);
        
        
        try {
            initComponents();
            loadData(top);
            repaint();
            setLenguaje();
        } catch (SQLException ex) {
            System.out.println(ex);
            //this.view.setStatusMessageLabel("Error al cargar tests", Color.red);
            JOptionPane.showMessageDialog(null,"Error al cargar test","Error",JOptionPane.ERROR_MESSAGE);
        } catch (ClassNotFoundException ex) {
            System.out.println(ex);
            //this.view.setStatusMessageLabel("Error al cargar tests", Color.red);
            JOptionPane.showMessageDialog(null,"Error al cargar test","Error",JOptionPane.ERROR_MESSAGE);
        }
    }

        /** Carga datos de la base de datos a un Jtree
         * @param top 
        */ 
        private void loadData(DefaultMutableTreeNode top) throws SQLException, ClassNotFoundException {

        DefaultMutableTreeNode asignatura = null;
        DefaultMutableTreeNode test = null;

        top = new DefaultMutableTreeNode("Asignaturas");

        List<Asignatura> asignaturas = fachada.seleccionarAsignaturas();

        for (Asignatura asig : asignaturas) {
            asignatura = new DefaultMutableTreeNode(asig);
            if(!asig.getTests().isEmpty()){
                top.add(asignatura);
                for (Test tes : asig.getTests()) {
                    test = new DefaultMutableTreeNode(tes);
                    asignatura.add(test);
                }
            }
        }
        DefaultTreeModel modelo = new DefaultTreeModel(top);
        this.testTree.setModel(modelo);
    }
        
        /** Borra los datos seleccionados del Jtree, también los borra de la bbdd
         * 
         * @throws ClassNotFoundException
         * @throws SQLException
         */
        public void deleteSelectedItems() throws ClassNotFoundException, SQLException {
        DefaultMutableTreeNode node;
        DefaultTreeModel model = (DefaultTreeModel) (testTree.getModel());
        TreePath[] paths = testTree.getSelectionPaths();
        for (int i = 0; i < paths.length; i++) {
            node = (DefaultMutableTreeNode) (paths[i].getLastPathComponent());
            
            if (node.getLevel()==1){
                Asignatura a = (Asignatura) node.getUserObject();
                List<Test> listaTests = fachada.seleccionarTests(a);
                for(Test t : listaTests){
                    fachada.eliminarTest(t);
                }
            }
            else if (node.getLevel()==2){
                Test t = (Test) node.getUserObject();
                fachada.eliminarTest(t);
            }
            
            if (node.getParent().getChildCount() == 1){
                node = (DefaultMutableTreeNode) (paths[i].getPathComponent(1));
                model.removeNodeFromParent(node);
            }
            else{
                model.removeNodeFromParent(node);
            }
        }
  }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        testTree = new javax.swing.JTree();
        btnBorrarTest = new javax.swing.JButton();

        setClosable(true);
        setName("Form"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        testTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        testTree.setName("testTree"); // NOI18N
        jScrollPane1.setViewportView(testTree);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(occho.OcchoApp.class).getContext().getResourceMap(BorrarTestsFrame.class);
        btnBorrarTest.setText(resourceMap.getString("btnBorrarTest.text")); // NOI18N
        btnBorrarTest.setName("btnBorrarTest"); // NOI18N
        btnBorrarTest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBorrarTestActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnBorrarTest)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 423, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(36, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(23, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(7, 7, 7)
                .addComponent(btnBorrarTest)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnBorrarTestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBorrarTestActionPerformed
        try {
            deleteSelectedItems();
            this.view.setStatusMessageLabel("Operación realizada", Color.BLACK);
        } catch (ClassNotFoundException ex) {
            System.out.println(ex);
            //this.view.setStatusMessageLabel("Error en la operación", Color.red);
            JOptionPane.showMessageDialog(null,"Error en la operación","Error",JOptionPane.ERROR_MESSAGE);
        }
          catch (
            SQLException ex) {System.out.println(ex);
            JOptionPane.showMessageDialog(null,"Error en la operación","Error",JOptionPane.ERROR_MESSAGE);
          }
    }//GEN-LAST:event_btnBorrarTestActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBorrarTest;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree testTree;
    // End of variables declaration//GEN-END:variables

    /**
     * Establece lenguaje
     */
    public void setLenguaje() {
        btnBorrarTest.setText(Messages.getString("btnBorrarTest.text", Messages.BUNDLE_NAME_BORRAR_TESTS));
        setTitle(Messages.getString("Form.title", Messages.BUNDLE_NAME_BORRAR_TESTS));
    }
}
